package fi.jamk.ourcookingapp.adapter;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import fi.jamk.ourcookingapp.R;
import fi.jamk.ourcookingapp.backend.architecture.services.DownloadImageService;
import fi.jamk.ourcookingapp.backend.model.Receipt;

/**
 * Adapter for showing a receipt
 * @author Marius
 */
public class MyReceiptAdapter extends ArrayAdapter<Receipt> {

	private final Context context;
	
	private List<Receipt> lstReceipts;

	private int resource;
	
	public MyReceiptAdapter(Context context, int resource, List<Receipt> receipts) {
		super(context, resource, receipts);
		this.context = context;
		this.resource = resource;
		this.lstReceipts = receipts;
	}
	
	@SuppressLint("ViewHolder")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(resource, parent, false);
		Receipt receipt = lstReceipts.get(position);
		
		// receipt image
		new DownloadImageService((ImageView) rowView.findViewById(R.id.receiptImage)).execute(receipt.getID() + ".png");
		
		// rececipt name
		TextView txtReceiptName = (TextView) rowView.findViewById(R.id.receiptName);
		txtReceiptName.setText(receipt.getName());
		
		// receipt description
		TextView txtDescription = (TextView) rowView.findViewById(R.id.receiptDescription);
		txtDescription.setText(receipt.getDescription());
		
		// rating stars
		int[] stars = {R.id.star1, R.id.star2, R.id.star3, R.id.star4, R.id.star5};
		int starsCount = (int)receipt.getRating();
		for (int i = 1; i <= starsCount; i++) {
			ImageView star = (ImageView) rowView.findViewById(stars[i - 1]);
			star.setImageResource(R.drawable.full_star);
		}
		// if the rating has 0.5 left
		if(receipt.getRating() % starsCount >= 0.5){
			ImageView star = (ImageView) rowView.findViewById(stars[starsCount]);
			star.setImageResource(R.drawable.half_star);
		}
		
		// receipt duration
		TextView txtDuration = (TextView) rowView.findViewById(R.id.receiptDuration);
		int hour = receipt.getDuration() / 60;
		int minutes = receipt.getDuration() - hour * 60;
		txtDuration.setText(hour + "h " + minutes + "m");
		
		// receipt clicks
		TextView txtClicks = (TextView) rowView.findViewById(R.id.receiptClicks);
		txtClicks.setText(receipt.getCountClicks() + "");
		
		// receipt effort
		TextView txtEffort = (TextView) rowView.findViewById(R.id.receiptEffort);
		txtEffort.setText(receipt.getEffort());
		return rowView;
	}

}
